import { getCookie } from '@tencent/gh-qqnews-sdk/gh-qqnews-utils';
import axios from 'axios';
import { jsonp } from './util';
import { TencentNewsReady } from './ready';
import { setContext as SentrySetContext } from '@sentry/vue';
type Account = 'qq'|'weixin';
export interface UserInfo{
  openid: string;
  nickname: string;
  headimgurl: string;
  account: Account|'other';
}
let userInfo: UserInfo;
// if (/^(10\.|localhost|127\.|192\.)/.test(location.hostname) || location.search.indexOf('__debug__') >= 0) {
//   // 测试
//   userInfo = {
//     headimgurl: 'https://thirdwx.qlogo.cn/mmopen/vi_32/ajNVdqHZLLDwYiblTKH75mBxOOeQWfDqHibDSiaIGtH0miasA7tlhxiavnleic4cicvfym2z21eOic7ia36qQG88R5mmRmw/132',
//     nickname: 'test',
//     // account: 'qq',
//     account: 'weixin',
//     // openid: '4BE75A3FE4FD25AD03426A45D772289B', // 孔 Q
//     // openid: 'o04Jg00fTaSoAgaTGIRVKDelACFQ', // 孔
//     // openid: 'o04Jg0-AUplaxT4lOFiIjVICjj5s', // other
//     openid: 'o04Jg0_HFO6V-aeb0e0u8WmnWt_M', // 帅/
//     // openid:'o04Jg00lE8rk6glXPIR-64bOHFuo', // 涛
//   };
//   // const width = window.innerWidth;
//   // window.onload = () => {
//   //   setTimeout(() => {
//   //     alert(`${width} ${window.innerWidth} ${navigator.userAgent}`);
//   //   }, 1000);
//   // };
// }
export default function getUserInfo(userType: 'all'|'qq'|'weixin' = 'all', force = true): Promise<UserInfo|null> {
  return new Promise<UserInfo|null>((resolve) => {
    if (userInfo) {
      resolve(userInfo);
    } else {
      if (/MicroMessenger/i.test(navigator.userAgent)) {
        // 微信客户端
        // @ts-ignore
        jsonp('https://yc.static.qq.com/?service=App.Getinfo_Getinfo.getindex').then((args: any[]) => {
          const { data } = args[0];
          if (!data || !data.openid) {
            if (force) {
              document.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc823e489fab1a34a&redirect_uri=${
                encodeURIComponent(`https://yc.static.qq.com/?service=App.Getinfo_Getinfo.Getuserinfo&original_uri=${encodeURIComponent(location.href)}`)
              }&response_type=code&scope=snsapi_userinfo&state=${encodeURIComponent(location.href)}#wechat_redirect`;
            } else {
              resolve(null);
            }
          } else {
            userInfo = {
              account: 'weixin',
              openid: data.openid,
              nickname: data.nickname,
              headimgurl: data.headimgurl,
            };
            console.log(userInfo);
            SentrySetContext('UserInfo', userInfo);
            resolve(userInfo);
          }
        });
      } else if (/qqnews/i.test(navigator.userAgent)) {
        // 新闻客户端
        TencentNewsReady.then((TencentNews: any) => {
          function getUserInfo(info: {
            account: UserInfo['account']|'',
            isWeakLogin: boolean,
            qq: {
              icon: string,
              name: string,
              mediaid: string,
              uin: string,
              viptype: number,
            },
            weixin: {
              icon: string,
              name: string,
              mediaid: string,
              uin: string,
              viptype: number,
            }
          }) {
            if (info.account && info[info.account as Account]) {
              if (userType === info.account || userType === 'all') {
                userInfo = {
                  account: info.account,
                  openid: info[info.account as Account].uin || info[info.account as Account].mediaid,
                  nickname: info[info.account as Account].name,
                  headimgurl: info[info.account as Account].icon,
                };
                if (!userInfo.openid) {
                  if (info.account === 'weixin') {
                    userInfo.openid = getCookie('openid') || '';
                  } else if (info.account === 'qq') {
                    userInfo.openid = getCookie('open_openid') || '';
                  }
                }
                console.log(userInfo);
                SentrySetContext('UserInfo', userInfo);
                resolve(userInfo);
              } else if (force) {
                // 已登陆 但登陆类型不匹配
                TencentNews.invoke('changeMainAccount', {
                  type: userType,
                  onCallback() {
                    TencentNews.invoke('getUserInfo', { onCallback: getUserInfo });
                  },
                });
              } else {
                resolve(null);
              }
            } else if (force) {
              // 未登录
              TencentNews.invoke('login', {
                type: userType,
                onCallback() {
                  TencentNews.invoke('getUserInfo', { onCallback: getUserInfo });
                },
              });
            } else {
              resolve(null);
            }
          }
          TencentNews.invoke('getUserInfo', { onCallback: getUserInfo });
        });
      } else {
        // 其他用户
        const tempUserInfo = localStorage.getItem('tempUserInfo');
        if (tempUserInfo) {
          userInfo = JSON.parse(tempUserInfo);
          console.log(userInfo);
          SentrySetContext('UserInfo', userInfo);
          resolve(userInfo);
        } else if (force) {
          // 创建账号
          axios.get('https://stars.news.qq.com/?service=App.Answer_FoundAParty.getopenid').then(({ data }) => {
            if (+data.ret === 200) {
              userInfo = {
                account: 'other',
                openid: data.data.openid,
                nickname: '腾讯网友',
                headimgurl: 'https://new.inews.gtimg.com/tnews/ae763feb/8933/ae763feb-8933-47dc-9247-0118dc40b935.jpg',
              };
              localStorage.setItem('tempUserInfo', JSON.stringify(userInfo));
              console.log(userInfo);
              SentrySetContext('UserInfo', userInfo);
              resolve(userInfo);
            }
          });
        } else {
          resolve(null);
        }
      }
    }
  }).then((userInfo) => {
    if (userInfo && !userInfo.openid) {
      return null;
    }
    return userInfo;
  });
}
